package cn.ulyer.generator.rest;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.ZipUtil;
import cn.ulyer.common.model.PageableVo;
import cn.ulyer.common.utils.PageResult;
import cn.ulyer.common.utils.Result;
import cn.ulyer.generator.model.GeneratorModel;
import cn.ulyer.generator.service.GeneratorService;
import cn.ulyer.generator.vo.TableVo;
import com.google.common.io.Files;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Profile;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;

@RestController
@RequestMapping("/generator")
@Slf4j
@Profile(value = {"test","dev"})
public class GeneratorRest {


    //or Map<String,DataSource>
    @Autowired
    private DataSource dataSource;

    @Autowired
    private GeneratorService generatorService;


    @GetMapping("/tables")
    public Result<PageResult<TableVo>> pageTable(PageableVo pageableVo,String tableName){
        return Result.ok().data(generatorService.queryTables(dataSource,pageableVo,tableName));
    }


    @PostMapping("/gen")
    public void gen(@RequestBody GeneratorModel generatorModel, HttpServletResponse response) throws IOException {
        response.setCharacterEncoding("utf-8");
        response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
        response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode("code.zip","UTF-8"));
        File tempDir = Files.createTempDir();
        log.info("生成临时文件夹:{}",tempDir.getPath());
        File baseFolder = new File(tempDir.getAbsolutePath()+"/"+generatorModel.getPackagePath().replaceAll("\\.","/"));
        if(!baseFolder.exists()){
            baseFolder.mkdirs();
        }
        log.info("代码临时文件夹:{}",baseFolder.getPath());
        BufferedOutputStream o = new BufferedOutputStream(response.getOutputStream());

        try{
            generatorService.generator(generatorModel,dataSource,baseFolder.getAbsolutePath(),"element2");
            File zip = ZipUtil.zip(tempDir.getAbsolutePath());
            FileInputStream inputStream = new FileInputStream(zip);
            o.write(IoUtil.readBytes(inputStream));
            inputStream.close();
            FileUtil.del(tempDir);
        }catch (Exception e){
            log.error("generator fail ：{}",e);
        }finally {
            o.flush();
            o.close();
        }

    }


    public static void main(String[] args) {
        File file = Files.createTempDir();
        System.out.println(file.getAbsoluteFile());
    }

}
